#include "PreCmpHeader.h"



void port_init(void)
{
	 PORTA = 0x00;
	 DDRA  = 0x00;
	 PORTB = 0x00;
	 DDRB  = 0x00;
	 PORTC = 0x00; //m103 output only
	 DDRC  = 0x00;
	 PORTD = 0xFF;
	 DDRD  = 0x08;
	 //PORTE = 0x00;
	 //DDRE  = 0x00;
	 PORTE = 0xFF;
	 DDRE  = 0x22;
	 PORTF = 0x00;
	 DDRF  = 0x00;
	 PORTG = 0x00;
	 DDRG  = 0x00;
}

//TIMER0 initialize - prescale:32
// WGM: Normal
// desired value: 1mSec
// actual value:  1.000mSec (0.0%)
void timer0_init(void)
{
	TCCR0 = 0x00; //stop
	ASSR  = 0x00; //set async mode
	TCNT0 = 0xD5; //set count
	OCR0  = 0x2B;
	TCCR0 = 0x06; //start timer
}

ISR(TIMER0_OVF_vect)
{
	TCNT0 = 0xD5; //reload counter value
	TaskRun_1ms = 1;
}

//TIMER1 initialize - prescale:1024
// WGM: 0) Normal, TOP=0xFFFF
// desired value: 1Sec
// actual value:  1.000Sec (0.0%)
void timer1_init(void)
{
	TCCR1B = 0x00; //stop
	TCNT1H = 0x57; //setup
	TCNT1L = 0x40;
	OCR1AH = 0xA8;
	OCR1AL = 0xC0;
	OCR1BH = 0xA8;
	OCR1BL = 0xC0;
	OCR1CH = 0xA8;
	OCR1CL = 0xC0;
	ICR1H  = 0xA8;
	ICR1L  = 0xC0;
	TCCR1A = 0x00;
	TCCR1B = 0x04; //start Timer
}

ISR(TIMER1_OVF_vect)
{
	TCNT1H = 0x57; //setup
	TCNT1L = 0x40;
	TaskRun_1s = 1;
}

//call this routine to initialize all peripherals
void init_devices(void)
{
	//stop errant interrupts until set up
	//CLI(); //disable all interrupts
	SREG = 0x00;
	XDIV  = 0x00; //xtal divider
	XMCRA = 0x00; //external memory
	port_init();
	timer0_init();
	timer1_init();
	uart0_init();
	uart1_init();

	MCUCR = 0x00;
	EICRA = 0x00; //extended ext ints
	EICRB = 0x00; //extended ext ints
	EIMSK = 0x00;
	TIMSK = 0x05; //timer interrupt sources
	ETIMSK = 0x00; //extended timer interrupt sources
	SREG = 0x80;//enable interrupts

	 //
	//SREG = 0x00;
	//XDIV  = 0x00; //xtal divider
	//XMCRA = 0x00; //external memory
	//port_init();
	//timer0_init();
	//timer1_init();
	//uart0_init();
	//uart1_init();
//
	//MCUCR = 0x00;
	//EICRA = 0x00; //extended ext ints
	//EICRB = 0x00; //extended ext ints
	//EIMSK = 0x00;
	//TIMSK = 0x05; //timer interrupt sources
	////TIMSK = 0x00; //timer interrupt sources
	//ETIMSK = 0x00; //extended timer interrupt sources
	//ADCSRA = 0x00; //disable adc
	//ACSR = 0x00; //ensure interrupt is off before changing
	//SREG = 0x80;//enable interrupts
	////all peripherals are now initialized
}